package com.hrma.controller;

import com.github.pagehelper.Page;
import com.hrma.entity.*;
import com.hrma.services.AchievementService;
import com.hrma.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/achievement")
@Slf4j
public class AchievementController {
    @Autowired
    private final AchievementService achievementService;

    public AchievementController(AchievementService achievementService) {
        this.achievementService = achievementService;
    }

    @PostMapping("/add")
    public Result<Achievement> add(@Validated @RequestBody Achievement data) {
        log.debug("收到add请求，请求参数：{}", data);
        return Result.ok(achievementService.add(data));
    }

    @DeleteMapping("/delete/{id}")
    public Result<?> delete(@PathVariable int id) {
        log.debug("收到delete请求，请求参数：{}", id);
        achievementService.delete(id);
        return Result.ok(null);
    }

    @PatchMapping("/update")
    public Result<?> update(@RequestBody Achievement data) {
        log.debug("收到update请求，请求参数：{}", data);
        achievementService.update(data);
        return Result.ok(null);
    }

    @GetMapping("/select")
    public Result<List<SelectResult>> select() {
        log.debug("收到select请求！");
        return Result.ok(achievementService.select());

    }

    @PostMapping("/list")
    public Result<ListWithCount<Achievement>> getList(@RequestBody AchievementDTO data) {
        log.debug("收到list请求，请求参数：{}", data);
        Page<Achievement> res = achievementService.getList(data);

        return Result.ok(new ListWithCount<>(res.getTotal(), res));
    }

    @PostMapping("/uploadAchievement")
    public Result<?> uploadAchievement(MultipartHttpServletRequest request) {
        log.debug("收到uploadAttendance请求!");
        request.getMultiFileMap().forEach((name, f) -> {
            try {
                achievementService.handleUpload(f.get(0));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        return Result.ok(null);
    }
}
